#include "comm.hpp"

Init init;

string TranToHex(key_t k)
{
    char buffer[32];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

int main()
{
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("create key success", Debug) << " server key is " << TranToHex(k) << endl;

    int shmid = shmget(k, SHM_SIZE, IPC_CREAT | 0666);
    if (shmid == -1)
    {
        perror("shmget error");
        exit(1);
    }
    Log("create shm success", Debug) << " shmid is " << shmid << endl;

    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    Log("attach shm success", Debug) << " shmid is " << shmid << endl;

    int fd = OpenFIFO(FIFO_NAME, READ);
    while (true)
    {
        Wait(fd);
        printf("%s\n", shmaddr);
        if (strcmp(shmaddr, "quit") == 0)
            break;
    }

    int ret = shmdt(shmaddr);
    if (ret == -1)
    {
        perror("shmdt error");
        exit(2);
    }
    Log("detach shm success", Debug) << " shmid is " << shmid << endl;
    
    ret = shmctl(shmid, IPC_RMID, nullptr);
    if (ret == -1)
    {
        perror("shmctl error");
        exit(3);
    }
    Log("delete shm success", Debug) << " shmid is " << shmid << endl;
    CloseFIFO(fd);
    return 0;
}